package com.yunchao.library.socket.model.connection

import com.yunchao.library.socket.constants.Values
import com.yunchao.library.socket.constants.Errors
import com.yunchao.library.socket.constants.Limits
import com.yunchao.library.socket.extensions.putString
import com.yunchao.library.socket.utils.BufferPool
import com.yunchao.library.socket.utils.ValidationUtils

data class HardwareDescriptor(
    val id: String,
    val version: String,
    val token: Int = Values.DEFAULT_TOKEN,
    val prefix: String = "yunchao",
    val provider: String = "yunchao",
    val label: String = "shouchi",
    val model: String = "YC-SeuicPDA",
    val heartbeat: Int = Values.DEFAULT_HEARTBEAT
) {
    init {
        require(id.isNotBlank()) { Errors.INVALID_DEVICE_ID }
        require(version.isNotBlank()) { Errors.INVALID_VERSION }
        ValidationUtils.validateString(prefix, "Prefix")
        ValidationUtils.validateString(provider, "Provider")
        ValidationUtils.validateString(label, "Label")
        ValidationUtils.validateString(model, "Model")
        require(heartbeat >= 0) { "Heartbeat must be non-negative" }
    }

    fun toByteArray(): ByteArray {
        return BufferPool.use(Limits.MAX_BUFFER_SIZE) { buffer ->
            buffer.apply {
                putInt(token)
                putString(id)
                putString(prefix)
                putString(provider)
                putString(version)
                putString(label)
                putString(model)
                putShort(heartbeat.toShort())
            }
            buffer.array().copyOf(buffer.position())
        }
    }
}